package com.houger.ddd.common.utils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by yangjiayong on 2018-4-8.
 */
public class ClassTypeUtils {

    private final static Lock LOCK = new ReentrantLock();

    public static Class[] getTypeArguments(Class objectClass) {
        LOCK.lock();
        try {
            Type t = objectClass.getGenericSuperclass();
            if (t instanceof ParameterizedType) {
                Type[] types = ((ParameterizedType) t).getActualTypeArguments();
                Class[] classes = new Class[types.length];
                for (int i = 0; i < types.length; i++) {
                    classes[i] = (Class) types[i];
                }
                return classes;
            }
        } finally {
            LOCK.unlock();
        }
        return new Class[0];
    }

    public static Object newInstance(String clazzName) {
        try {
            Class clazz = Class.forName(clazzName);
            return newInstance(clazz);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        throw new RuntimeException(clazzName + "不存在");
    }

    public static Object newInstance(Class clazz) {
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            return instance;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        throw new RuntimeException(clazz.getName() + "实例化失败,缺少无参构造函数");
    }
}
